/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccstore;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 *
 * @author berto
 */
public class WebappContextListener implements ServletContextListener {

    public WebappContextListener(){
    }
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        /*
         * Creo solo una volta la connessione con il database
         */
        String dburl= sce.getServletContext().getInitParameter("db_url");
        String dbuser= sce.getServletContext().getInitParameter("db_user");
        String dbpsw= sce.getServletContext().getInitParameter("db_password");
        try{
            DBManager manager=new DBManager(dburl,dbuser,dbpsw);
            //Pubblico l'attributo per il context
            sce.getServletContext().setAttribute("db_manager", manager);
        }catch(Exception ex){
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        try{
            DBManager manager=(DBManager) sce.getServletContext().getAttribute("db_manager");
            if(manager!=null){
                manager.close();
            }
        }catch(Exception ex){
            throw new RuntimeException(ex);
        }
    }
    
}
